package com.cdpowernode.pncrm.controller;

import com.cdpowernode.pncrm.exception.CrmException;
import com.cdpowernode.pncrm.javabean.*;
import com.cdpowernode.pncrm.service.ActivityService;
import com.cdpowernode.pncrm.service.UserService;
import com.cdpowernode.pncrm.utils.Constant;
import com.cdpowernode.pncrm.utils.CrmDateUtil;
import com.cdpowernode.pncrm.utils.UUIDUtil;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author jy
 * @version 1.0
 * @date 2021/12/4 9:28
 */
@Controller
@RequestMapping("/workbench")
public class WorkbenchController {

    @Autowired
    private UserService userService;
    @Autowired
    private ActivityService activityService;

    @RequestMapping("/main/index")
    public String mainIndex() {
        return "workbench/main/index";
    }

    @RequestMapping("/activity/index")
    public String toActivityIndex(Model model, ActivityVo activityVo){
        List<User> userList = userService.findAll();
        model.addAttribute("userList",userList);
        return "workbench/activity/index";
    }

    @RequestMapping("/activity/detail")
    public String toActivityDetail(Model model,String id){
        Activity activity = activityService.findById(id);
        model.addAttribute("activity",activity);
        return "workbench/activity/detail";
    }

    /**
     * 添加市场活动
     */
    @RequestMapping("/activity/addActivity")
    @ResponseBody
    public ReturnObject addActivity(Activity activity, HttpSession session){
        ReturnObject ro = new ReturnObject();

        //手动为activity添加id
        activity.setId(UUIDUtil.getUuid());
        //手动为activity添加创建时间
        activity.setCreateTime(CrmDateUtil.dateToString(new Date()));
        //手动为activity添加创建者的id
        activity.setCreateBy(((User)session.getAttribute(Constant.SESSION_LOGIN_USER)).getId());

        try {
            activityService.addActivity(activity);
            ro.setCode(1);
        }catch (Exception e){
            e.printStackTrace();
            ro.setCode(0);
            if (e instanceof CrmException){
                ro.setMsg(e.getMessage());
            }else {
                ro.setMsg("系统异常!");
            }
        }
            return ro;
    }

    /**
     * 根据条件查询
     * @param activityVo
     * @return
     */
    @RequestMapping("/activity/findByCondition")
    @ResponseBody
    public ReturnObject findByCondition(ActivityVo activityVo){
        ReturnObject ro = new ReturnObject();
        try {
            PageInfo<Activity> pageInfo = activityService.findByCondition(activityVo);
            ro.setCode(1);
            ro.setData(pageInfo);
        }catch (Exception e){
            e.printStackTrace();
            ro.setCode(0);
            ro.setMsg("系统异常！");
        }
        return ro;
    }

    /**
     * 根据id查找，点击修改后把后端传值填充对应输入框
     * @param id
     * @return
     */
    @RequestMapping("/activity/findById")
    @ResponseBody
    public ReturnObject findById(String id){
        ReturnObject ro = new ReturnObject();
        try {
           Activity activity = activityService.findById(id);
            ro.setCode(1);
            ro.setData(activity);
        }catch (Exception e){
            e.printStackTrace();
            ro.setCode(0);
            ro.setMsg("系统异常！");
        }
        return ro;
    }

    @RequestMapping("/activity/updateActivity")
    @ResponseBody
    public ReturnObject updateActivity(Activity activity,HttpSession session){
        ReturnObject ro = new ReturnObject();
        activity.setEditTime(CrmDateUtil.dateToString(new Date()));
        activity.setEditBy(((User)session.getAttribute(Constant.SESSION_LOGIN_USER)).getId());
        try {
            activityService.updateActivity(activity);
            ro.setCode(1);
        }catch (Exception e){
            if (e instanceof CrmException){
                ro.setMsg(e.getMessage());
            }else {
                ro.setMsg("系统异常！");
            }
            ro.setCode(0);
        }
        return ro;
    }

    @RequestMapping("/activity/deleteActivity")
    @ResponseBody
    public ReturnObject deleteActivity(String[] ids){
        ReturnObject ro = new ReturnObject();
        try {
            boolean flag = activityService.deleteActivityById(ids);
            if (flag){
                ro.setCode(1);
            }else {
                ro.setCode(0);
            }
        }catch (Exception e){
            if (e instanceof CrmException){
                ro.setMsg(e.getMessage());
            }else {
                ro.setMsg("系统异常！");
            }
        }
        return ro;
    }

    /**
     * 导出所有市场活动
     * @param response
     * @throws IOException
     */
    @RequestMapping("/activity/exportActivityAll")
    public void exportActivityAll(HttpServletResponse response) throws IOException, IllegalAccessException {
        //1.查询所有的市场活动
        List<Activity> activityList = activityService.findAll();
        //2.创建工具类对象
        HSSFWorkbook wb = new HSSFWorkbook();
        //3.创建xls文件
        HSSFSheet sheet = wb.createSheet();

        //为xls文件添加表头
        createTitleForSheet(sheet);
        //为xls文件添加具体的内容
        createDataForSheet(sheet,activityList);

        //3.设置响应头，告诉浏览器响应的数据不需要展示，而应该作为附件下载
        response.setContentType("application/octet-stream");//告诉浏览器不用展示
        //告诉浏览器需要下载附件
        response.setHeader("Content-Disposition","attachment;filename=activityList.xls");
        //4.将xls文件写给浏览器
        //将response的输出流交给wb工具类对象进行写出
        wb.write(response.getOutputStream());
        wb.close();
        response.getOutputStream().flush();
    }

    //将指定集合中的没有给市场活动的数据取出并添加到指定的表格中
    private void createDataForSheet(HSSFSheet sheet, List<Activity> activityList) throws IllegalAccessException {
        for (int i = 0; i < activityList.size(); i++) {
            Activity activity = activityList.get(i);
            HSSFRow row = sheet.createRow(i + 1);
            //使用反射的方式进行内容填充
            Class<Activity> aClass = Activity.class;
            Field[] fields = aClass.getDeclaredFields();
            int index = 0;
            for (int j = 0; j < fields.length; j++) {
                Field f = fields[j];
                f.setAccessible(true);//开启当前属性的访问权限
                if(f.getName().equals("owner") || f.getName().equals("createBy") || f.getName().equals("editBy") || f.getName().equals("serialVersionUID")) {
                    continue;
                }
                HSSFCell cell = row.createCell(index++);
                if (f.getName().endsWith("User")){
                    if (f.get(activity) == null){
                        cell.setCellValue("无");
                    }else {
                        cell.setCellValue(((User) f.get(activity)).getName());
                    }
                }else {
                    cell.setCellValue((String) f.get(activity));
                }
            }
        }

    }

    //为指定的xls文件创建标题
    private void createTitleForSheet(HSSFSheet sheet) {
        //为表格创建第一行
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell0 = row.createCell(0);//为第一行创建第一列
        cell0.setCellValue("id");//为第一列的内容赋值
        //以下是为第一行的所有列进行赋值，标题用中文，便于客户阅读
        HSSFCell cell1 = row.createCell(1);
        cell1.setCellValue("所有者");
        HSSFCell cell2 = row.createCell(2);
        cell2.setCellValue("名称");
        HSSFCell cell3 = row.createCell(3);
        cell3.setCellValue("开始时间");
        HSSFCell cell4 = row.createCell(4);
        cell4.setCellValue("结束时间");
        HSSFCell cell5 = row.createCell(5);
        cell5.setCellValue("花费金额");
        HSSFCell cell6 = row.createCell(6);
        cell6.setCellValue("描述");
        HSSFCell cell7 = row.createCell(7);
        cell7.setCellValue("创建时间");
        HSSFCell cell8 = row.createCell(8);
        cell8.setCellValue("创建者");
        HSSFCell cell9 = row.createCell(9);
        cell9.setCellValue("修改时间");
        HSSFCell cell10 = row.createCell(10);
        cell10.setCellValue("修改者");
    }

    /**
     * 选择导出市场活动
     * @param response
     */
    @RequestMapping(value = "/activity/exportActivityXz",method = RequestMethod.GET)
    @ResponseBody
    public void exportActivityXz(HttpServletResponse response,String[] id) throws IllegalAccessException, IOException {
        //1.查询勾选的市场活动
        List<Activity> activityList = activityService.findXzById(id);
        //2.创建工具类对象
        HSSFWorkbook wb = new HSSFWorkbook();
        //3.创建xls文件
        HSSFSheet sheet = wb.createSheet();

        //为xls文件添加表头
        createTitleForSheet(sheet);
        //为xls文件添加具体的内容
        createDataForSheet(sheet,activityList);

        //3.设置响应头，告诉浏览器响应的数据不需要展示，而应该作为附件下载
        response.setContentType("application/octet-stream");//告诉浏览器不用展示
        //告诉浏览器需要下载附件
        response.setHeader("Content-Disposition","attachment;filename=activityIdList.xls");
        //4.将xls文件写给浏览器
        //将response的输出流交给wb工具类对象进行写出
        wb.write(response.getOutputStream());
        wb.close();
        response.getOutputStream().flush();
    }

    /**
     * 导入市场活动
     * @param mf
     * @param session
     * @return
     * @throws IOException
     */
    @PostMapping("/activity/importActivity")
    @ResponseBody
    public ReturnObject importActivity(@RequestParam("activityFile") MultipartFile mf,HttpSession session) throws IOException {
        ReturnObject ro = new ReturnObject();
        //相当于拿到了上传的文件的所有内容
        InputStream inputStream = mf.getInputStream();
        //创建工具类对象
        HSSFWorkbook wb = new HSSFWorkbook(inputStream);
        //相当于取出了上传的表格文件
        HSSFSheet sheet = wb.getSheetAt(0);
        List<Activity> activityList = new ArrayList<>();
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            //相当于取出每一行
            HSSFRow row = sheet.getRow(i);
            //将每一行解析为Activity对象
            Activity activity = handleRowToActivity(row,session);
            activityList.add(activity);
        }
        try {
            activityService.addActivityList(activityList);
            ro.setCode(1);
        }catch (Exception e){
            ro.setCode(0);
            ro.setMsg("系统异常");
        }
        return ro;
    }

    /**
     * 将指定表格的指定行的内容解析为一个Activity对象
     * @param row
     * @param session
     * @return
     */
    private Activity handleRowToActivity(HSSFRow row, HttpSession session) {
        Activity activity = new Activity();
        activity.setId(UUIDUtil.getUuid());
        activity.setOwner(((User)session.getAttribute(Constant.SESSION_LOGIN_USER)).getId());
        activity.setCreateTime(CrmDateUtil.dateToString(new Date()));
        activity.setCreateBy(((User)session.getAttribute(Constant.SESSION_LOGIN_USER)).getId());

        HSSFCell cell0 = row.getCell(0);
        if (cell0 != null){
            activity.setName(cell0.getStringCellValue());
        }
        HSSFCell cell1 = row.getCell(1);
        if (cell1 != null){
            activity.setStartDate(cell1.getStringCellValue());
        }
        HSSFCell cell2 = row.getCell(2);
        if (cell2 != null){
            activity.setEndDate(cell2.getStringCellValue());
        }
        HSSFCell cell3 = row.getCell(3);
        if (cell3 != null){
            activity.setCost(cell3.getStringCellValue());
        }
        HSSFCell cell4 = row.getCell(4);
        if (cell4 != null){
            activity.setDescription(cell4.getStringCellValue());
        }
        return activity;
    }

    /**
     * 进入市场活动详情页时，正确显示下面根据Id对应的备注信息
     * @param id
     * @return
     */
    @RequestMapping("/activity/getRemarkListByAid")
    @ResponseBody
    public ReturnObject getRemarkListByAid(String id){
        ReturnObject ro = new ReturnObject();
        try {
            List<ActivityRemark> arList =  activityService.getRemarkListByAid(id);
            ro.setCode(1);
            ro.setData(arList);
        }catch (Exception e){
            e.printStackTrace();
            ro.setCode(0);
            ro.setMsg("系统异常！");
        }
        return ro;
    }

    /**
     * 在备注信息处根据Id进行删除备注
     * @param id
     */
    @RequestMapping(value = "/activity/deleteRemark",method = RequestMethod.POST)
    @ResponseBody
    public ReturnObject deleteRemark(String id){
        ReturnObject ro = new ReturnObject();
        try {
            boolean flag = activityService.deleteRemark(id);
            if (flag){
                ro.setCode(1);
            }else {
                ro.setCode(0);
            }
        }catch (Exception e){
            if (e instanceof CrmException){
                ro.setMsg(e.getMessage());
            }else {
                ro.setMsg("系统异常！");
            }
        }
        return ro;
    }

    /**
     * 在备注信息处添加备注
     * @param id
     */
    @RequestMapping(value = "/activity/saveRemark",method = RequestMethod.POST)
    @ResponseBody
    public ReturnObject saveRemark(@RequestParam("noteContent") String noteContent,String id,HttpSession session) {
        ActivityRemark ar = new ActivityRemark();
        ar.setId(UUIDUtil.getUuid());
        ar.setNoteContent(noteContent);
        ar.setCreateTime(CrmDateUtil.dateToString(new Date()));
        ar.setCreateBy(((User) session.getAttribute(Constant.SESSION_LOGIN_USER)).getName());
        ar.setEditFlag("0");
        ar.setActivityId(id);
        ReturnObject ro = new ReturnObject();
        try {
            boolean flag = activityService.saveRemark(ar);
            if (flag) {
                ro.setData(ar);
                ro.setCode(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ro.setCode(0);
            ro.setMsg("系统异常！");
        }
        return ro;
    }
}
